<template>
    <div class="edit-dialog-container">
        <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px" destroy-on-close>
            <el-tabs type="border-card" @tab-click="changeTabs">
                <el-tab-pane label="导入人员">
                    <div style="display: flex;">
                        <div style="width: 50%;">
                            <div>
                                从第 <el-input-number controls-position="right" v-model="state.options.dataIndex" size="small"
                                    :min="1" :step="1" />&nbsp;行开始
                            </div>
                            <div>
                                <el-checkbox v-model="state.options.code.isSettled" disabled /> <el-link>{{ '工号'
                                }}</el-link>
                                ,第 <el-input-number controls-position="right" v-model="state.options.code.colNo"
                                    size="small" :min="1" :step="1" />&nbsp;列
                            </div>
                            <div>
                                <el-checkbox v-model="state.options.name.isSettled" /> <el-link>{{ '姓名' }}</el-link>
                                ,第 <el-input-number controls-position="right" v-model="state.options.name.colNo"
                                    size="small" :min="1" :step="1" />&nbsp;列
                            </div>
                            <div>
                                <el-checkbox v-model="state.options.icCode.isSettled" /> <el-link>{{ '卡号' }}</el-link>
                                ,第 <el-input-number controls-position="right" v-model="state.options.icCode.colNo"
                                    size="small" :min="1" :step="1" />&nbsp;列
                            </div>
                            <div>
                                <el-checkbox v-model="state.options.orgCode.isSettled" /> <el-link>{{ '部门编号' }}</el-link>
                                ,第 <el-input-number controls-position="right" v-model="state.options.orgCode.colNo"
                                    size="small" :min="1" :step="1" />&nbsp;列
                            </div>
                            <div>
                                <el-checkbox v-model="state.options.roleCode.isSettled" /> <el-link>{{ '角色编号' }}</el-link>
                                ,第 <el-input-number controls-position="right" v-model="state.options.roleCode.colNo"
                                    size="small" :min="1" :step="1" />&nbsp;列
                            </div>
                        </div>
                        <div style="width: 50%;"> <el-upload class="upload-demo" limit="1" drag action="#" multiple
                                :on-change="handleChange" :http-request="uploadHttpRequest">
                                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                                <div class="el-upload__text">
                                    拖动文件 或&nbsp
                                    <em>点击选择</em>
                                </div>
                                <template #tip>
                                    <div class="el-upload__tip">
                                        选择 1 个 xls/xlsx 文件
                                    </div>
                                </template>
                            </el-upload></div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="导入人脸照片">
                    <div style="display: flex;">
                        <div style="width: 100%;"> <el-upload class="upload-demo" drag action="#" multiple
                                :on-change="handleBiophotoChange" :http-request="uploadHttpRequest">
                                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                                <div class="el-upload__text">
                                    拖动文件 或&nbsp
                                    <em>点击选择</em>
                                </div>
                                <template #tip>
                                    <div class="el-upload__tip" style="font-size: 14px;">
                                        注意：照片名称命名格式为 工号.格式 例：1001.jpg
                                    </div>
                                </template>
                            </el-upload></div>
                    </div>
                </el-tab-pane>
            </el-tabs>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onSubmit" type="success" size="default">{{ t('message.btnName.submit')
                    }}</el-button>
                    <el-button @click="onCancel" size="default">{{ t('message.btnName.cancel') }}</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" >
import { reactive, toRaw } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage, UploadProps } from 'element-plus';
import { readXlsxFile } from '/@/utils/xlsx';
import { usePersonImportApi, useImportBiophotoApi } from '/@/api/person/employee';
import { usePersonRoleListApi } from '/@/api/person/role';
import { usePersonOrgListApi } from '/@/api/person/org';
import { fileToBase64 } from '/@/utils/files'

// 定义子组件向父组件传值/事件
const { t } = useI18n();
const emit = defineEmits(['refresh']);

// 定义变量内容
interface ObjType {
    code: string,
    name: string,
    orgCode: string,
    roleCode: string,
    geoCode: string,
    privilege: string,
}

const state = reactive({
    dialog: {
        isShowDialog: false,
        type: 0,
        title: '导入人员信息',
    },
    // Options: ['工号', '姓名','部门', '角色'],
    options: {
        dataIndex: 2,
        code: { isSettled: true, colNo: 1, text: 'code', tag: '工号' },
        name: { isSettled: false, colNo: 2, text: 'name', tag: '姓名' },
        icCode: { isSettled: false, colNo: 3, text: 'icCode', tag: '卡号' },
        orgCode: { isSettled: false, colNo: 4, text: 'orgCode', tag: '部门编号' },
        roleCode: { isSettled: false, colNo: 5, text: 'roleCode', tag: '角色编号' },
    } as any,
    checkedOptions: [] as string[],
    fileList: [] as any,
    orgData: [] as any,
    roleData: [] as any,
    biophotoList: [] as any,
});

const changeTabs = () => {
    if (state.dialog.type === 1) {
        state.dialog.title = '导入人员信息'
        state.dialog.type = 0
    }
    else {
        state.dialog.title = '导入人脸照片'
        state.dialog.type = 1
    }
}

// 提交
const onSubmit = () => {
    if (state.dialog.type === 0) {
        if (state.fileList.length !== 0) {
            usePersonImportApi(state.fileList).then(() => {
                ElMessage.success('导入成功');
                state.fileList = []
                emit('refresh');
            }).then(() => {
                closeDialog()
            })
        }
        else {
            ElMessage.error('请选择文件1');
        }
    }
    else {
        if (state.biophotoList.length !== 0) {
            useImportBiophotoApi(state.biophotoList).then(() => {
                ElMessage.success('导入成功');
                state.fileList = []
                emit('refresh');
            }).then(() => {
                closeDialog()
            })
        }
        else {
            ElMessage.error('请选择文件');
        }
    }
};

// 文件上传
const handleChange = (file: any, fileList: any) => {
    readXlsxFile(file.raw).then((res: any) => {
        if(res.length!==0){
        let checkOptions = Object.keys(state.options).filter(key => state.options[key].isSettled === true).map(key => state.options[key].tag)
        res = res.filter((item: any) => item.__rowNum__ >= state.options.dataIndex - 1) 
        res.forEach((item: any) => {
            let obj = {} as any
            let keys = Object.keys(item)
            keys.forEach((key, idx) => {
                if (checkOptions.includes(key)) {
                    if (idx === state.options.code.colNo - 1) {
                        obj[state.options.code.text] = item[key] + ''
                    }
                    if (idx === state.options.name.colNo - 1) {
                        obj[state.options.name.text] = item[key] + ''
                    }
                    if (idx === state.options.icCode.colNo - 1) {
                        obj[state.options.icCode.text] = item[key] + ''
                    }
                    if (idx === state.options.orgCode.colNo - 1) {
                        // obj[state.options.orgCode.text] = state.orgData[item[key]]
                        obj[state.options.orgCode.text] = item[key]+ ''
                    }
                    if (idx === state.options.roleCode.colNo - 1) {
                        // obj[state.options.roleCode.text] = state.roleData[item[key]]
                        obj[state.options.roleCode.text] = item[key]+ ''
                    }
                }
            })
            state.fileList.push(obj)
        })
        }
        else {
            ElMessage.error('读取失败，请检查文件内容');
        }

    })
}

// 文件上传
const handleBiophotoChange = (file: any) => {
    fileToBase64(toRaw(file.raw)).then((res) => {
        state.biophotoList.push({
            code: file.name.split('.')[0],
            biophoto: res
        });
    })
}

const uploadHttpRequest = (data: any) => {
    // console.log(data);
}

// 打开弹窗
const openDialog = (code?: string) => {
    state.dialog.isShowDialog = true
    usePersonRoleListApi().then(({ content }) => {
        content.forEach((item: any) => {
            state.roleData[item.name] = item.code
        })
    })
    usePersonOrgListApi().then(({ content }) => {
        content.forEach((item: any) => {
            state.orgData[item.name] = item.code
        })
    });
}

// 关闭弹窗
const closeDialog = () => {
    state.dialog.isShowDialog = false;
    emit('refresh');
};
// 取消
const onCancel = () => {
    closeDialog();
};

defineExpose({
    openDialog,
});
</script>


<style scoped lang="scss">
:deep(.el-dialog__header) {
    margin: 0;
    border-bottom: 1px dashed rgba(0, 0, 0, .2);
}

:deep(.el-dialog__footer) {
    border-top: 1px dashed rgba(0, 0, 0, .2);
}
</style>